import React from "react";
import {
  Row,
  Col,
  Input,
  Select,
  Drawer,
  Button,
  Spin,
  Modal,
  Space,
  Breadcrumb,
  Table,
  message,
  Popconfirm,
  Form,
  Upload,
  Tooltip,
  Tag,
} from "antd";
import {
  EyeFilled,
  InboxOutlined,
  DeleteFilled,
  PlusCircleOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import { Link } from "react-router-dom";
import {
  _getUserName,
  _paperTypeList,
  _addPaper,
  _delPaper,
  _myPaperList,
} from "../../util/api/paper/index";
const up_api = require("../../util/upload");
const { confirm } = Modal;
const { Dragger } = Upload;
const { Option } = Select;
const url = require("../../util/conUrl");

class NewsList extends React.Component {
  state = {
    selectedRowKeys: [], // Check here to configure the default column
    isLoading: false,
    a_visible: false,
    // userNameList: [],
    gradeList: [],
    confirmLoading: false,
    typeName: "",
    myPaperList: null,
    is_upload: false,
    //
    paperData: {},
  };
  getData = () => {
    this.setState({ isLoading: true });
    let user_id = JSON.parse(localStorage.getItem("c_user")).user_id;

    _myPaperList(user_id)
      .then((res) => {
        if (res.status === 200 && res.data.code === 0) {
          this.setState({ isLoading: false });
          const myPaperList = res.data.data;
          for (let i = 0; i < myPaperList.length; i++) {
            myPaperList[i].key = myPaperList[i].paper_id;
            myPaperList[i].control = myPaperList[i].paper_id;
          }
          this.setState({ myPaperList: myPaperList });
        }
      })
      .catch(() => {
        this.setState({ isLoading: false });
        message.error("服务器错误");
      });
  };
  componentDidMount = () => {
    this.getData();
  };

  deletSource = (val) => {
    _delPaper(val)
      .then((res) => {
        console.log(res.data);
        if (res.status === 200 && res.data.code === 0) {
          if (res.data.data && res.data.data.code === -1) {
            message.warning(res.data.data.msg);
          } else {
            message.success("删除成功");
            this.getData();
          }
        }
      })
      .catch(() => {
        this.setState({ isLoading: false });
        message.error("服务器错误");
      });
  };
  onSelectChange = (selectedRowKeys) => {
    console.log("selectedRowKeys changed: ", selectedRowKeys);
    this.setState({ selectedRowKeys });
  };
  showDrawer = () => {
    this.setState({
      a_visible: true,
    });
    // _getUserName().then((res) => {
    //   this.setState({ userNameList: res.data.data });
    // });
    _paperTypeList().then((res) => {
      this.setState({ gradeList: res.data.data });
    });
  };
  onFinish = (val) => {
    let self = this;
    // let paper_name = val.paper_name.join(", ");
    let paper_url = val.paper_url.fileList[0].response.data.data.filename;
    let user_id = JSON.parse(localStorage.getItem("c_user")).user_id;
    let tempData = {
      paper_title: val.paper_title,
      paper_name: val.paper_name,
      grade_id: val.grade_id,
      paper_time: val.paper_time,
      paper_url: paper_url,
      user_id: user_id,
    };
    confirm({
      title: "请再次确认提交信息！",
      icon: <ExclamationCircleOutlined />,
      content: (
        <div>
          <p>名称：{val.paper_title}</p>
          <p>作者：{val.paper_name}</p>
          <p>年份：{val.paper_time}</p>
        </div>
      ),
      onOk() {
        _addPaper(tempData).then((res) => {
          if (res.status === 200 && res.data.code === 0) {
            message.success("提交成功", 1.5).then(() => {
              self.setState({ a_visible: false });
              self.getData();
            });
          }
        });
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };

  handleCancel = () => {
    this.setState({
      e_visible: false,
      a_visible: false,
    });
  };
  onInputChange = (e) => {
    this.setState({ typeName: e.target.value });
  };

  handleChange(value) {
    console.log(`selected ${value}`);
  }
  onFileChange = (info) => {
    const { status } = info.file;
    if (status !== "uploading") {
    }
    if (status === "done") {
      setTimeout(() => {
        message.success(`${info.file.name} 上传成功！`, 2);
        this.setState({ is_upload: true });
      }, 1500);
    } else if (status === "error") {
      message.error(`${info.file.name} 上传失败！`);
    }
  };
  render() {
    const columns = [
      {
        title: "名称",
        dataIndex: "paper_title",
      },
      {
        title: "作者",
        dataIndex: "paper_name",
      },
      {
        title: "会议/期刊",
        dataIndex: "grade_name",
        render: (text, record) => <Tag color="blue">{text}</Tag>,
      },
      {
        title: "操作",
        dataIndex: "control",
        render: (text, record) => (
          <Space size="middle">
            {/* <a href={`/view_p?url=${record.paper_url}`} target="_blank" rel="noopener noreferrer">
                <EyeFilled />
              </a> */}
            <a
              href={`/file/paper/${record.paper_url}`}
              target="_blank"
              rel="noopener noreferrer"
            >
              <EyeFilled />
            </a>
            <Popconfirm
              title="确认要删除吗？"
              okText="是"
              cancelText="否"
              onConfirm={this.deletSource.bind(this, text)}
            >
              <DeleteFilled style={{ color: "#7f8c8d" }} />
            </Popconfirm>
            {/* <Tooltip placement="topLeft" title="下载">
              <Button
                type="primary"
                shape="circle"
                icon={<DownloadOutlined />}
                size="small"
                href={url.api + "/file/paper/" + record.paper_url}
              />
            </Tooltip> */}
          </Space>
        ),
      },
    ];

    const props = {
      name: "file",
      multiple: false,
      action: up_api.api.up_paper,
      accept: ".pdf",
    };
    return (
      <div>
        <div className="newslist-header">
          <Breadcrumb style={{ margin: "16px 0" }}>
            <Breadcrumb.Item>
              <Link to="/m/index">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>我的论文</Breadcrumb.Item>
          </Breadcrumb>

          <div>
            <Button
              icon={<PlusCircleOutlined />}
              onClick={this.showDrawer}
              type="primary"
            >
              提交论文
            </Button>
          </div>
        </div>

        <div className="admin-body" style={{ padding: 15, minHeight: 360 }}>
          <Spin tip="Loading..." spinning={this.state.isLoading}>
            <Table
              columns={columns}
              dataSource={this.state.myPaperList}
              pagination={{ pageSize: 6 }}
            />
          </Spin>

          <Drawer
            placement="left"
            closable={false}
            onClose={this.handleCancel}
            visible={this.state.a_visible}
            width="46vw"
          >
            <Form
              name="basic"
              initialValues={{
                remember: true,
              }}
              onFinish={this.onFinish}
            >
              <Form.Item
                label="论文题目"
                name="paper_title"
                rules={[
                  {
                    required: true,
                    message: "请填写论文题目!",
                  },
                ]}
              >
                <Input size="large" allowClear />
              </Form.Item>
              <Form.Item
                label="论文作者"
                name="paper_name"
                rules={[
                  {
                    required: true,
                    message: "请选择论文作者!",
                  },
                ]}
              >
                {/* <Select
                  mode="multiple"
                  style={{ width: "100%" }}
                  placeholder="论文作者"
                  // defaultValue={["a10", "c12"]}
                  onChange={this.handleChange}
                  size="large"
                  allowClear
                >
                  {this.state.userNameList.map((v) => (
                    <Option value={v.user_cname} key={v.user_id}>
                      {v.user_name}
                    </Option>
                  ))}
                </Select> */}
                <Input size="large" allowClear />
              </Form.Item>
              <Form.Item
                label="会议/期刊"
                name="grade_id"
                rules={[
                  {
                    required: true,
                    message: "请选择论文级别!",
                  },
                ]}
              >
                <Select
                  placeholder="会议/期刊"
                  allowClear
                  size="large"
                  style={{ width: "100%" }}
                  allowClear
                >
                  {this.state.gradeList.map((v) => (
                    <Option value={v.grade_id} key={v.grade_id}>
                      {v.grade_name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>

              <Form.Item
                label="论文年份"
                name="paper_time"
                rules={[
                  {
                    required: true,

                    message: "请填写年份（如：2020）!",
                  },
                ]}
              >
                <Input
                  size="large"
                  placeholder="请填写年份（如：2020）!"
                  allowClear
                />
              </Form.Item>
              <Form.Item
                label="PDF文件"
                name="paper_url"
                rules={[
                  {
                    required: true,
                    message: "请上传你的文件!",
                  },
                ]}
              >
                <Dragger
                  {...props}
                  onChange={this.onFileChange}
                  disabled={this.state.is_upload}
                >
                  <p className="ant-upload-drag-icon">
                    <InboxOutlined />
                  </p>
                  <p className="ant-upload-text">点击或者拖拽上传你的论文</p>
                  <p className="ant-upload-hint">请选择正确的PDF文本格式</p>
                </Dragger>
              </Form.Item>

              <Form.Item>
                <Row>
                  <Col span={4} offset={20}>
                    <Button type="primary" htmlType="submit" size="large">
                      提交论文
                    </Button>
                  </Col>
                </Row>
              </Form.Item>
            </Form>
          </Drawer>
        </div>
      </div>
    );
  }
}

export default NewsList;
